package com.example.mypigcar.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

public class JWTUtils {
    /**
     * 签名
     */
    private static final String TOKEN = "token!Q@W3e4r";
    /**
     * 时长
     */
    public final static long keepTime =  24 * 60 * 60 * 1000;
    /**
     * 生成token
     * @param map  //传入payload
     * @return 返回token
     */
    public static String getToken(Map<String,String> map)  {
        Date expiresAt = new Date(System.currentTimeMillis() + keepTime);
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        builder.withExpiresAt(expiresAt);
        return builder.sign(Algorithm.HMAC256(TOKEN)).toString();
    }
    /**
     * 验证token
     * @param token
     * @return
     */
    public static void verify(String token)  {
        JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }
    /**
     * 获取token中payload
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token)  {
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }


    /**
     * 根据token获取用户名
     * @param request request
     * @return 用户名
     */
    public static String getUsernameByToken(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        DecodedJWT token1 = JWTUtils.getToken(token);
        Map<String, Claim> claims = token1.getClaims();
        return claims.get("username").asString();
    }

    /**
     * 根据token获取用户ID
     * @param request request
     * @return 用户名
     */
    public static String getUserIdByToken(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        DecodedJWT token1 = JWTUtils.getToken(token);
        Map<String, Claim> claims = token1.getClaims();
        return claims.get("userID").asString();
    }
}
